<template>
	<view>
		<view style='padding:15px;'>
			<u--form :model="formData" ref="form1">
				<u-form-item label="企业名称" prop="ownerName" @click="enterpriseClick" placeName="'请输入企业名称'"
					labelWidth='220'>
					<u--input v-model="formData.ownerName" placeholder="请选择企业名称" readonly>
					</u--input>
				</u-form-item>
				<u-form-item label="询查日期" prop="patrolTime" @click="showTime = true;" labelWidth='220'>
					<uni-datetime-picker type="datetime" v-model="formData.patrolTime" @change="showSelect=false"
						:disabled="supervisionType.type=='view'" />
				</u-form-item>
				<u-form-item label="询查人员" prop="patrolName"
					@click="supervisionType.type == 'view'?showCheckSelect  = false:showCheckSelect = true;"
					placeName="'请输入询查人员'" labelWidth='220'>
					<u--input v-model="formData.patrolName" placeholder="请选择询查人员" readonly>
					</u--input>
				</u-form-item>
				<u-form-item label="询查内容" prop="patrolContent" labelWidth='220'>
					<u--textarea :disabled="supervisionType.type=='view'" v-model="formData.patrolContent"
						placeholder="请输入询查内容" height='220'>
					</u--textarea>
				</u-form-item>
				<span style='display: block;'>检查事项</span>
				<view class="" style="width: 100%;margin: 10px 0;border: 1px #e2e4e7 solid;padding: 10px 0;">
					<!-- checkItems -->
					<view class="" v-for="(key,index) in checkItems" style="padding:  5px;"
						@click="checkItemsClick(key,index)">
						<span class='inspection_no' v-if="isIf">{{arrData[index]?arrData[index]:0}}</span>
						<span class='inspection_no' v-else>0</span>
						{{key.inspItemGeneraName}}
						<u-icon label="" size="40" name="arrow-right" style='float: right;margin: 5px 0 0 0;'></u-icon>
					</view>

				</view>
				<u-form-item label="是否需要整改" prop="isRisks" labelWidth='220'>
					<u-radio-group v-model="formData.isRisks" placement="row" size='40'
						:disabled="supervisionType.type=='view'">
						<u-radio activeColor="#1590EF" label="是" name='1' style='padding:0 60rpx 0 0' labelSize='30'>
						</u-radio>
						<u-radio activeColor="#1590EF" label="否" name='0' labelSize='30'></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="询查情况" prop="patrolResult" labelWidth='220'
					v-if="supervisionType.type=='view'?formData.patrolResult:true">
					<u--textarea v-model="formData.patrolResult" placeholder="请输入询查情况" height='150'
						:disabled="supervisionType.type=='view'">
					</u--textarea>
				</u-form-item>
				<u-form-item prop="patrolResult" v-if="supervisionType.type=='view'&&formData.patrolResult?false:true">
					<text
						style="width: 110px;display: inline-block;">{{supervisionType.type!=='view'?'':supervisionType.type=='view'&&formData.patrolResult?'':'询查情况'}}</text>
					<view class="file-list clearfix">
						<view class="file-item" v-for="(item,index) in formData.patrolResultFiles">
							<image class="file-img" :src="item.temp" mode="aspectFit"
								@click="previewImage(item,index,1)">
							</image>
							<view class="file-del" @click="fileDel(index,1)"></view>
						</view>
						<view class="file-item file-upload-btn" @click="selectFile(1)"></view>
					</view>
				</u-form-item>
				<u-form-item label="询查意见" prop="patrolOpinion" labelWidth='220'>
					<u--textarea v-model="formData.patrolOpinion" placeholder="请输入询查意见" height='150'
						:disabled="supervisionType.type=='view'">
					</u--textarea>
				</u-form-item>
				<u-form-item label="企业现场负责人" prop="dutyPerson" labelWidth='250'>
					<u--input v-model="formData.dutyPerson" placeholder="请输入企业负责人"
						:disabled="supervisionType.type=='view'">
					</u--input>
				</u-form-item>

				<u-form-item prop="file" borderBottom label="询查附件" labelWidth='220'>
					<view class="file-list clearfix">
						<view class="file-item" v-for="(item,index) in formData.files">
							<image class="file-img" :src="item.temp" mode="aspectFit"
								@click="previewImage(item,index,2)">
							</image>
							<view class="file-del" @click="fileDel(index,2)"></view>
						</view>
						<view class="file-item file-upload-btn" @click="selectFile(2)"></view>
					</view>
				</u-form-item>
				<view class="" style="width: 100%;text-align: center;" v-if="supervisionType.type!=='view'">
					<text type="primary" class="add" @click="clickSave(1)">保存</text>
					<text type="primary" class="add" @click="clickSave(2)" v-if="supervisionType.type=='add'">提交</text>
					<text type="primary" class="add" @click="clickSave(2)"
						v-else-if="(supervisionType.inspStatus!=='1'&&supervisionType.type=='edit')">提交</text>
				</view>
			</u--form>
			<!--单选 企业-->
			<!-- <qianziyuSelect :show="showSelect" type="radio" :dataLists="columnsCompany" @cancel="showSelect=false"
				@groupChange="confirmSelect" @search='search' format="changeRadio">
			</qianziyuSelect> -->

			<!--单选 企业-->
			<select-task ref="goodsName1" @change="hwNameListChange"></select-task>

			<!-- 多选 人员 -->
			<qianziyuSelect :show="showCheckSelect" type="checkbox" :dataLists="columnsName"
				@cancel="showCheckSelect=false" @submit="confirmSelect" @search='search'>
			</qianziyuSelect>
		</view>
		<!-- <canvas :style="{ height: lineBgHeight + 'px' }" canvas-id="myCanvas"></canvas> -->
		<canvas canvas-id="myCanvas" :style="{'width':w,'height': h}"
			style="position: absolute;left: -9999px;top: -9999px;"></canvas>

		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<record-maintenance :itemData='itemData' @changeSave='changeSave' :type='supervisionType.type'>
				</record-maintenance>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import qianziyuSelect from '@/components/qianziyu-select/qianziyu-select.vue'
	import selectTask from '@/components/tool-select/select-task.vue'
	import * as api from '@/common/api/supervision.js'
	import recordMaintenance from './recordMaintenance'
	import {
		deepClone,
	} from '@/common/util.js'
	export default {
		components: {
			qianziyuSelect,
			recordMaintenance,
			selectTask
		},
		data() {
			return {
				showSelect: false,
				showTime: false,
				showCheckSelect: false,
				isIf: false,
				formData: {
					ownerId: "",
					ownerName: "",
					patrolTime: "",
					patrolContent: "",
					isRisks: "",
					patrolResult: "",
					patrolOpinion: "",
					dutyPerson: "",
					patrolName: "",
					patrolPers: [],
					files: [],
					patrolResultFiles: [],
					inspRecordList: []

				},
				columnsCompany: [],
				companyList: [],

				nameList: [],
				columnsName: [],

				supervisionType: {
					Sid: "",
					type: '',
					inspStatus: ""
				},
				w: 0,
				h: 0,
				checkItems: [],
				itemData: [],
				arrData: [],
				arrIndex: 0,
				arrList: [],
			}
		},
		onLoad(option) {
			this.supervisionType = option
		},
		mounted() {

			this.$api.getDeptUserList(this.$store.state.userInfo.dept_id, this.$store.state.userInfo.tenant_id).then(
				res => {

					res.data.data.forEach((item) => {
						this.columnsName.push({
							id: item.id,
							name: item.name,
							ischeck: false
						});

						this.nameList.push({
							id: item.id,
							name: item.name,
						});
					});
				})

			// 详情查询
			if (this.supervisionType.type !== 'add') {
				this.isIf = false
				let num = 0
				api.default.getSupervisionDetail(this.supervisionType.Sid).then(res => {
					this.formData = res.data.data
					this.formData.patrolName = ''
					res.data.data.patrolPers.forEach(item => {
						this.formData.patrolName += item.perName + ','
					})
					res.data.data.files.forEach(item => {
						item.temp = item.url
					})

					if (res.data.data.patrolResultFiles.length != 0) {
						res.data.data.patrolResultFiles.forEach(item => {
							item.temp = item.url
						})
					}

					this.checkItems = res.data.data.inspItemList

					res.data.data.inspItemList.map((item, index) => {
						this.checkItems[index].itemList = this.initTable(item.itemList)
						item.itemList.map(items => {
							if (items.selected == true) {
								num++
							}
						})
						this.arrData[index] = num
						num = 0
					})
					this.isIf = true
					// temp
					this.formData.patrolName = this.formData.patrolName.substring(0, this.formData.patrolName
						.lastIndexOf(
							','));
				})
			}

			if (this.supervisionType.type == 'add') {
				// 检查事项
				api.default.getCheckItems().then(res => {
					this.checkItems = res.data.data
				})

			}
		},
		methods: {
			// 新增保存
			clickSave(i) {
				let arr = [{
					key: 'ownerName',
					value: "企业名称"
				}, {
					key: 'patrolTime',
					value: "询查日期"
				}, {
					key: 'patrolName',
					value: "询查人员"
				}, {
					key: 'patrolContent',
					value: "询查内容"
				}, {
					key: 'isRisks',
					value: "是否需要整改"
				}, {
					key: 'patrolOpinion',
					value: "询查意见"
				}, {
					key: 'dutyPerson',
					value: "企业现场负责人"
				}]


				for (let i = 0; i < arr.length; i++) {
					if (!this.formData[arr[i].key]) {
						uni.showToast({
							title: arr[i].value + '不能为空！',
							icon: 'none',
							duration: 1000
						});
						return
					}
				}

				if (!this.formData.patrolResult && this.formData.patrolResultFiles.length == 0) {
					uni.showToast({
						title: '询查情况不能为空！',
						icon: 'none',
						duration: 1000
					});
					return
				}

				if (this.formData.files.length == 0) {
					uni.showToast({
						title: '询查附件不能为空！',
						icon: 'none',
						duration: 1000
					});
					return
				}


				// 新增询查
				if (this.supervisionType.type == 'add' && i == 1) {
					api.default.getSupervisionSave(this.formData).then(res => {
						uni.showToast({
							title: '保存成功！',
							icon: 'success',
							duration: 2000
						})
						this.$goBack('./patrolName?index=0', 5)
					})
				}

				if (this.supervisionType.type == 'add' && i == 2) {
					api.default.getSupervisionSubmit(this.formData).then(res => {
						uni.showToast({
							title: '提交成功！',
							icon: 'success',
							duration: 2000
						})
						this.$goBack('./patrolName?index=0', 5)
					})
				}

				if (this.supervisionType.type == 'edit') {
					let num = 0;

					if (this.supervisionType.inspStatus == 0) {
						num = 0;
					}
					if (this.supervisionType.inspStatus == 1) {
						num = 1;
					}

					let arrList = []
					let arrData = []
					var formData = {}
					this.checkItems.map(i => {
						formData = i.itemList.map((item) => {
							const inspOpt = [],
								inspBlank = [];
							item.inspResult.forEach((obj) => {
								if (obj.checked) {
									inspOpt.push({
										key: obj.checked,
									});
								}
							});
							item.inspRecord.map((obj) => {
								if (obj.blankValue) {
									inspBlank.push({
										key: obj.dictKey,
										value: obj.blankValue,
									});
								}
							});
							return {
								inspItemId: item.id,
								inspOpt,
								inspBlank,
							};
						});
						arrList.push(...formData)
					})

					arrList.map((key, index) => {
						if (key.inspOpt.length !== 0 || key.inspBlank.length !== 0) {
							arrData.push(key)
						}
					})
					this.formData.inspRecordList = arrData

					if (i == 1) {
						api.default.getSupervisionUpdate(this.formData, i).then(res => {
							uni.showToast({
								title: '保存成功！',
								icon: 'success',
								duration: 2000
							})
							this.$goBack('./patrolName?index=' + num, 5)
						})
					} else {
						api.default.getSupervisionUpdate(this.formData, i).then(res => {
							uni.showToast({
								title: '提交成功！',
								icon: 'success',
								duration: 2000
							})
							this.$goBack('./patrolName?index=' + num, 5)
						})
					}
				}

			},

			// 把查询到的每个项目的结果、记录项进行分组处理
			initGroup(list) {
				const res = [];
				const arr = [];
				for (let a = 0; a < list.length; a++) {
					if (list[a].children) {
						return list
					}
				}
				list.forEach((item) => {
					let index = arr.indexOf(item.dictGroup);
					if (index === -1) {
						arr.push(item.dictGroup);
						index = arr.length - 1;
						res[index] = {
							checked: "",
							children: [],
						};
					}
					if (item.selected) {
						res[index].checked = item.dictKey;
					}
					res[index].children.push(item);
				});
				return res;
			},

			//初始化表格 
			initTable(tableData) {
				tableData = deepClone(tableData);
				let PTI = 0;
				tableData.forEach((item, i) => {
					const prev = tableData[PTI];
					item.inspResult = this.initGroup(item.inspResult);
					// item.inspRecord = this.initGroup(item.inspRecord);
					if (prev.inspItemCode === item.inspItemCode) {
						if (prev.rowspan) {
							prev.rowspan += 1;
						} else {
							prev.rowspan = 1;
						}
					} else {
						PTI = i;
						item.rowspan = 1;
					}
				});
				return tableData;
			},

			// 右滑菜单
			checkItemsClick(item, index) {
				this.arrIndex = index
				this.itemData = item
				const arr = this.formData.inspRecordList.map(k => {
					return k.inspItemId
				})
				// 如果选中没点保存则清空
				if (!this.arrData[index]) {
					item.itemList.map(key => {
						key.inspResult.map(i => {
							i.checked = ""
						})
					})
				} else {
					item.itemList.map(keys => {
						if (!arr.includes(keys.id)) {
							keys.inspResult.map(i => {
								i.checked = ""
							})
						}

					})
				}

				this.$refs.popup.open('right')
			},

			// 保存
			changeSave(item) {
				this.isIf = false
				let num = 0
				this.arrList.push(...item)
				this.formData.inspRecordList = this.unRepeat(this.arrList)
				this.$refs.popup.close()
				item.map(key => {
					if (key.inspOpt.length !== 0 || key.inspBlank.length !== 0) {
						num++
					}
				})
				this.arrData[this.arrIndex] = num
				this.isIf = true

			},

			unRepeat(arr) {
				const res = new Map();
				return arr.filter((arr) => !res.has(arr.inspItemId) && res.set(arr.inspItemId, 1))
			},
			// 人员/企业 确定
			confirmSelect(e) {
				// // 企业
				// if (this.aNum == 1) {
				// 	this.formData.ownerName = e.name
				// 	this.formData.ownerId = e.id
				// 	this.showSelect = false
				// }
				// 人员
				// if (this.aNum == 2) {
				let arr = []
				this.formData.patrolName = ""
				e.map(item => {
					this.formData.patrolName += item.name + ','
					this.formData.patrolPers.push({
						"perId": item.id, //询查人员名称
						"perName": item.name //检查人员名称多个逗号隔开
					})
					// 回显
					this.columnsName.map((items, index) => {
						if (items.id == item.id) {
							arr.push(index)
							this.columnsName[index].ischeck = true
						} else if (!arr.includes(index)) {
							this.columnsName[index].ischeck = false
						}
					})
				})
				// 去除末尾逗号
				this.formData.patrolName = this.formData.patrolName.substring(0, this.formData.patrolName.lastIndexOf(
					','));
				this.showCheckSelect = false
				// }

			},

			// 搜索查询
			search(keyword) {
				const aArr = ['columnsName']
				let arrList = []
				if (keyword == '') {
					this.columnsName = this.nameList
				} else {
					this[aArr[0]].forEach(item => {
						if (item.name.indexOf(keyword) != -1) {
							arrList.push(item)
						}
					})
					this[aArr[0]] = arrList
				}
			},

			//企业选择 
			enterpriseClick() {
				this.$refs.goodsName1.showBox({
					title: "请选择企业名称",
					data: 0,
					key: "",
					getData: (key) => {
						return new Promise((resolve) => {
							this.$api.findOwner().then((res) => {
								// console.log(2,res.data.data)
								resolve(res.data.data);
							}).catch(res => {});
						})
					}
				});
			},

			//货物信息-名称list
			hwNameListChange(res) {
				let item = res.item;
				this.formData.ownerName = item.ownerName
				this.formData.ownerId = item.ownerId
					
			},

			previewImage(val, index, type) {
				if (type == 1) {
					let photoList = this.formData.patrolResultFiles.map(item => {
						return item.temp;
					});
					uni.previewImage({
						current: index, // 当前显示图片的索引值
						urls: photoList, // 需要预览的图片列表，photoList要求必须是数组
						loop: true, // 是否可循环预览
					})
				} else {
					let photoList = this.formData.files.map(item => {
						return item.temp;
					});
					uni.previewImage({
						current: index, // 当前显示图片的索引值
						urls: photoList, // 需要预览的图片列表，photoList要求必须是数组
						loop: true, // 是否可循环预览
					})
				}
			},

			// 点击选择图片
			selectFile(index) {
				if (this.supervisionType.type == 'view') {
					return false
				}
				if (this.formData.files.length == 9 || this.formData.patrolResultFiles.length == 9) {
					uni.showToast({
						title: "最多上传9个",
						icon: 'none'
					})
					return;
				}
				uni.chooseImage({
					count: index == 2 ? (9 - this.formData.files.length) : 9 - this.formData.patrolResultFiles
						.length,
					sourceType: ['camera'], //这要注意，camera掉拍照，album是打开手机相册
					success: (chooseImageRes) => {
						this.addwatermark(chooseImageRes.tempFilePaths[0], chooseImageRes.tempFilePaths[0],
							index)
					}
				});
			},

			// 删除已上传的图片
			fileDel(index, type) {
				if (this.supervisionType.type == 'view') {
					return false
				}
				if (type == 1) {
					this.formData.patrolResultFiles.splice(index, 1)
				} else {
					this.formData.files.splice(index, 1)
				}
			},

			// 给照片添加水印
			addwatermark(imgVal, chooseImageRes, index) {
				var that = this
				var context = uni.createCanvasContext('myCanvas', this)
				uni.getImageInfo({
					src: imgVal,
					success: function(image) {
						that.w = image.width / 2 + 'px';
						that.h = image.height / 2 + 'px';
						setTimeout(function() {
							context.fillRect(0, 0, image.width / 2, image.height /
								2);
							// 将图片src放到cancas内，宽高为图片大小
							context.drawImage(imgVal, 0,
								0, image.width / 2, image.height / 2)
							context.beginPath()
							context.setFontSize(20)
							context.setFillStyle('red');
							context.fillText('拍照时间：' + new Date().toLocaleString(), 10, image.height /
								2 - 20)
							context.rotate(45 * Math.PI / 180);
							context.draw(false, setTimeout(() => {
								uni.canvasToTempFilePath({
									canvasId: "myCanvas",
									fileType: 'jpg',
									success: (path) => {
										uni.uploadFile({
											url: '/data-inspection-study/insp_file/upload',
											filePath: path
												.tempFilePath,
											name: 'file',
											success: (
												uploadFileRes) => {
												const fileData =
													uploadFileRes
													.data ? JSON
													.parse(
														uploadFileRes
														.data) : ''
												if (fileData &&
													fileData
													.code == 200) {
													uni.showToast({
														title: '上传成功',
														icon: 'none'
													})
													if (index ==
														2) {
														that.formData
															.files
															.push({
																id: fileData
																	.data
																	.id,
																temp: path
																	.tempFilePath
															})
													} else {
														that.formData
															.patrolResultFiles
															.push({
																id: fileData
																	.data
																	.id,
																temp: path
																	.tempFilePath
															})
													}

												}
											}
										});
									},
								})
							}, 500))
						}, 500)
					}
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.file-list {
		flex: 1;

		.file-item {
			float: left;
			width: 22%;
			text-align: center;
			height: 140rpx;
			line-height: 140rpx;
			margin-right: 4%;
			margin-bottom: 2%;
			position: relative;

			.file-img {
				max-width: 100%;
				max-height: 100%;
				vertical-align: middle;
			}

			.file-del {
				position: absolute;
				right: 0;
				top: 0;
				transform: translate(30%, -30%);
				border-radius: 50%;
				width: 0;
				height: 0;
				border: 20rpx solid #f00;

				&::after {
					content: "";
					width: 20rpx;
					display: block;
					transform: translate(-50%, -50%);
					background-color: #ffffff;
					height: 4rpx;
				}
			}

			&:nth-child(4n) {
				margin-right: 0;
			}

			&:nth-child(n+5) {
				margin-top: calc(4% / 3);
			}

		}

		.file-upload-btn {
			box-sizing: border-box;
			border: 1px solid #ddd;
			background: url('/static/img/camera.png') no-repeat center;
			background-size: 70%;
		}
	}

	.add {
		width: 30%;
		margin: 10px;
		display: inline-block;
		text-align: center;
		padding: 15rpx 20rpx;
		border-radius: 10px;
		background-color: #1590EF;
		color: white;
	}

	.inspection_no {
		border-radius: 50%;
		border: 2px #168fef solid;
		width: 25px;
		height: 25px;
		line-height: 25px;
		display: inline-block;
		text-align: center;
		color: #168fef;
		margin: 0 10px 0 0;
	}

	.popup-content {
		width: 300px;
	}
</style>
